﻿using System;
using System.Linq;
using System.Web.UI;
using Cotrobaie.UsersWebService;

namespace Cotrobaie
{
    public partial class Site1 : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            #region Javascript Claudia
            TextBoxUsername.Attributes.Add("onChange", "onUsernameTextChanged(this)");
            TextBoxUsername.Attributes.Add("onFocus", "textBoxUsername_onFocus(this)");
            TextBoxUsername.Attributes.Add("onBlur", "onUsernameFocusOut(this)");
            TextBoxUsername.Attributes.Add("onKeyUp", "onKeyUpUser(this)");
            TextBoxPassword.Attributes.Add("onChange", "onPasswordTextChanged(this)");
            TextBoxPassword.Attributes.Add("onFocus", "textBoxPassword_onFocus(this)");
            TextBoxPassword.Attributes.Add("onBlur", "onPasswordFocusOut(this)");
            TextBoxPassword.Attributes.Add("onKeyUp", "onKeyUpPass(this)");
            TextBoxSearch.Attributes.Add("onChange", "onSearchTextChanged(this)");
            TextBoxSearch.Attributes.Add("onFocus", "textBoxSearch_onFocus(this)");
            TextBoxSearch.Attributes.Add("onBlur", "onSearchFocusOut(this)");
            TextBoxSearch.Attributes.Add("onKeyUp", "onKeyUpUser(this)");
            meniuDinamic.InnerHtml = GenerateCategorii();
            #endregion

            if (NonPublic.UserIpuriBanate() >= 20 && (!Request.Url.ToString().Substring(0,Request.Url.ToString().Length-Request.QueryString.ToString().Length).Contains("Ban.aspx") &&
                !Request.Url.ToString().Substring(0, Request.Url.ToString().Length - Request.QueryString.ToString().Length).Contains("Contact.aspx"))) Response.Redirect("Ban.aspx");

            if (Session["UserID"] != null) UserLoggedIn(null);
            else UserLoggedOut();

            Page.Form.DefaultButton = ImageButton1.UniqueID;
            Page.Form.DefaultFocus = TextBoxSearch.UniqueID;



        }
        protected void ButtonLogin_Click(object sender, EventArgs e)
        {
            if (Session["UserID"] == null && TextBoxUsername.Visible)
            {
                using (UsersSoapClient serviciu = new UsersSoapClient("UsersSoap"))
                {
                    var result = serviciu.Login(TextBoxUsername.Text, TextBoxPassword.Text);
                    if (result.Success)
                    {
                        var user = result.User;
                        if (user != null)
                        {
                            UserLoggedIn(user);
                            if (Page.IsPostBack) Response.Redirect(Request.RawUrl);
                        }
                        else { ErrorText.InnerHtml = "Username inexistent"; ModalPopupExtender1.Show(); TextBoxPassword.Text = String.Empty; }
                    }
                    else { ErrorText.InnerHtml = result.Mesaj; ModalPopupExtender1.Show(); TextBoxPassword.Text = String.Empty; }
                }
            }
            else
            {
                UserLoggedOut();
                if (Page.IsPostBack) Response.Redirect(Request.RawUrl);
            }
        }
        private void UserLoggedIn(UsersWebService.TipUser user)
        {
            if (user != null)
            {
                Session["UserID"] = user.ID;
                Session["UserUsername"] = user.Username;
                Session["UserNume"] = user.Nume;
                Session["UserPrenume"] = user.Prenume;
                Session["UserParola"] = user.Parola;
                Session["UserEmail"] = user.Email;
            }
            HyperLinkwelcome.Text = ((Session["UserPrenume"].ToString() + " " + Session["UserNume"].ToString()).Length > 2 ? (Session["UserPrenume"].ToString() + " " + Session["UserNume"].ToString()) : Session["UserUsername"].ToString()) + "!";
            HyperLinkwelcome.NavigateUrl = "~/MyAccount.aspx";
            TextBoxUsername.Visible = TextBoxPassword.Visible = false;
            ButtonLogin.Text = "logout";

            HyperLinkBookmarks.NavigateUrl = "~/Bookmarks.aspx";
            HyperLinkSubscriptions.NavigateUrl = "~/Subscriptions.aspx";
            using (UsersSoapClient serviciu = new UsersSoapClient("UsersSoap"))
            {
                var result = serviciu.GetUserBookmarks((int)Session["UserID"], Session["UserUsername"].ToString(), Session["UserParola"].ToString(), 0, 1);
                if (result.Produse.Count() == 0)
                {
                    LiteralBookmarks.InnerText = "Bookmark list empty.";
                    LiteralBookmarks.Style.Add("left", "25px");
                }
                else
                {
                    detailsBookmark.Visible = true;
                    var b = result.Produse[0];
                    ImageBookmarks.ImageUrl = (b.imageLarge != null && b.imageLarge.Length > 0 ? b.imageLarge : (b.imageMedium != null && b.imageMedium.Length > 0 ? b.imageMedium : (b.imageSmall != null && b.imageSmall.Length > 0 ? b.imageSmall : "images/img.JPG")));
                    LiteralBookmark.InnerHtml = "<a href='" + b.linkSite + "'class = 'blgrlink'>" + b.name.Remove(50) +"</a> <br/> $" + b.Price.ToString();
                    
                }

                var result1 = serviciu.GetUserAlarms((int)Session["UserID"], Session["UserUsername"].ToString(), Session["UserParola"].ToString(), 0, 1);
                if (result1.Produse.Count() == 0)
                {
                    LiteralSubscriptions.InnerText = "No subscriptions yet.";
                    LiteralSubscriptions.Style.Add("left", "25px");
                }

                else
                {
                    detailsSubscriptions.Visible = true;
                    var b = result1.Produse[0];
                    ImageSubscriptions.ImageUrl = (b.imageLarge != null && b.imageLarge.Length > 0 ? b.imageLarge : (b.imageMedium != null && b.imageMedium.Length > 0 ? b.imageMedium : (b.imageSmall != null && b.imageSmall.Length > 0 ? b.imageSmall : "images/img.JPG")));
                    LiteralSubscription.InnerHtml = "<a href='" + b.linkSite + "'class = 'blgrlink'>" + b.name.Remove(50) + "</a> <br/> $" + b.Price.ToString();
                }
            }

        }
        private void UserLoggedOut()
        {
            Session["UserEmail"] = Session["UserID"] = Session["UserUsername"] = Session["UserNume"] = Session["UserPrenume"] = Session["UserParola"] = null;
            HyperLinkwelcome.Text = "guest!";
            HyperLinkwelcome.NavigateUrl = "~/Login.aspx";
            TextBoxUsername.Visible = TextBoxPassword.Visible = true;
            ButtonLogin.Text = "login";

            LiteralBookmarks.InnerText = "Log in to add products to your bookmarks! Find quick and easy any desired product.";
            LiteralBookmarks.Style.Add("position", "relative");
            LiteralBookmarks.Style.Add("left","20px");
            LiteralBookmarks.Style.Add("top", "15px");
            LiteralSubscriptions.InnerText = "Log in to subscribe to products! Follow via e-mail the evolution of prices!";
            LiteralSubscriptions.Style.Add("position", "relative");
            LiteralSubscriptions.Style.Add("left", "15px");
            LiteralBookmarks.Style.Add("top", "15px");
        }

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            if (TextBoxSearch.Text != String.Empty)
            {
                using (UsersSoapClient serviciu = new UsersSoapClient("UsersSoap"))
                {
                    string IDs = Hidden2.Value;
                    string Keys = String.Empty;
                    foreach (var v in HiddenKeyWords.Value.Split(new char[] { ';' }))
                        if (v.Length >= 4)
                        {
                            var resut = serviciu.AddKeyWord(v.Trim());
                            if (!resut.Success) { }

                            foreach (var v2 in TextBoxSearch.Text.Split(new char[] { ';' }))
                                if (v.Trim() == v2.Trim()) Keys += v2.Trim() + ";";
                        }

                    HiddenKeyWords.Value = Hidden1.Value = Hidden2.Value = String.Empty;
                    if (Keys == String.Empty && IDs != String.Empty && IDs.IndexOf(';') == IDs.LastIndexOf(';')) Response.Redirect("Product.aspx?ProductID=" + IDs.Replace(";",""));
                    if (Keys != String.Empty && IDs != String.Empty)
                        Response.Redirect("Search.aspx?KeyWord=" + Server.UrlEncode(Keys.Trim(new char[] { ' ', ';' })) + "&ProductsID=" + IDs.Trim(new char[] { ' ', ';' }) + "&Pg=0&IntrariPg=8");
                    else if (Keys != String.Empty) Response.Redirect("Search.aspx?KeyWord=" + Server.UrlEncode(Keys.Trim(new char[] { ' ', ';' })) + "&Pg=0&IntrariPg=8");
                    else if (IDs != String.Empty) Response.Redirect("Search.aspx?ProductsID=" + IDs.Trim(new char[] { ' ', ';' }) + "&Pg=0&IntrariPg=8");
                    else Response.Redirect("Search.aspx?KeyWord=" + Server.UrlEncode(TextBoxSearch.Text) + "&Pg=0&IntrariPg=8");
                }
            }
            else if (TextBoxUsername.Text != String.Empty && TextBoxPassword.Text != String.Empty)
                ButtonLogin_Click(null, null);
        }
        private string GenerateCategorii()
        {

            using (UsersSoapClient serviciu = new UsersSoapClient("UsersSoap"))
            {
                var result=serviciu.GetCategorii();
                if (result.Success)
                {
                    string meniu = String.Empty;
                    meniu += "<ul id='ulmenu'><li><a id='HyperLinkBooks' href='Search.aspx?categoryID=" + result.Categorii.Skip(0).First().ID.ToString() + "&Pg=0&IntrariPg=8' class= 'vmenulink' title='" + ToTitleCase(result.Categorii.Skip(0).First().description) + "'>" + ToTitleCase(result.Categorii.Skip(0).First().name) + "</a><a id ='ButtonBooks' onclick='showCat(this)' class='vmenulink'>-</a><ul id='books'>";
                    foreach (var v in result.Categorii.Skip(0).First().SubCategorii)
                        meniu += "<li><a id='HyperLink1' class= 'menulink' href='Search.aspx?categoryID=" + v.ID + "&Pg=0&IntrariPg=8' title='" + ToTitleCase(v.description) + "'>" + ToTitleCase(v.name) + "</a></li>";
                    meniu += "</ul></li><li><a id='HyperLinkMultimedia' href='Search.aspx?categoryID=" + result.Categorii.Skip(1).First().ID.ToString() + "&Pg=0&IntrariPg=8' class= 'vmenulink' title='" + ToTitleCase(result.Categorii.Skip(1).First().description) + "'>" + ToTitleCase(result.Categorii.Skip(1).First().name) + "</a><a id ='ButtonMultim' onclick='showCat(this)' class='vmenulink'>-</a><ul id='multim'>";
                    foreach (var v in result.Categorii.Skip(1).First().SubCategorii)
                        meniu += "<li><a id='HyperLink1' class= 'menulink' href='Search.aspx?categoryID=" + v.ID + "&Pg=0&IntrariPg=8' title='" + ToTitleCase(v.description) + "'>" + ToTitleCase(v.name) + "</a></li>";
                    meniu += "</ul></li><li><a id='HyperLinkElectronics' href='Search.aspx?categoryID=" + result.Categorii.Skip(2).First().ID.ToString() + "&Pg=0&IntrariPg=8' class= 'vmenulink' title='" + ToTitleCase(result.Categorii.Skip(2).First().description) + "'>" + ToTitleCase(result.Categorii.Skip(2).First().name) + "</a><a id ='ButtonElectr' onclick='showCat(this)' class='vmenulink'>-</a><ul id='electr'>";
                    foreach (var v in result.Categorii.Skip(2).First().SubCategorii)
                        meniu += "<li><a id='HyperLink1' class= 'menulink' href='Search.aspx?categoryID=" + v.ID + "&Pg=0&IntrariPg=8' title='" + ToTitleCase(v.description) + "'>" + ToTitleCase(v.name) + "</a></li>";
                    meniu += "</ul></li></ul>";
                    return meniu;
                }
            }
            return String.Empty;
        }

        private string ToTitleCase(string p)
        { return p.Substring(0, 1).ToUpper() + p.Substring(1); }
    }
}